# !/usr/bin/env/python3
# -*- coding: utf-8 -*-
# @Author  : 影子
# @Time    : 2024/2/1 14:13
# @Software: adb_terminal_tools
# @File    : applied_logic.py
# @Description: 应用逻辑
import datetime
import random
import string
import subprocess
import time as ti
from time import time
import json
import difflib
import re

from ttkbootstrap.dialogs import Messagebox
from ttkbootstrap.toast import ToastNotification

from main.logs import logger


def get_toast(title, message, style="Info"):
    """
    toast信息实现
    title：toast标题
    message：toast显示的消息
    style：toast显示样式
    """
    toast = ToastNotification(
        title=title,  # toast标题
        message=message,  # toast显示的消息
        duration=3000,  # Toast持续时间，单位为毫秒
        position=(500, 400, 'n'),  # Toast的位置，这里以左上角为原点
        bootstyle=style,
    )
    toast.show_toast()


def time_stamp():
    """时间戳函数"""
    return int(time())


def execute_command(cmd):
    """命令执行函数"""
    try:
        result = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT, text=True, encoding="utf-8",
                                         creationflags=subprocess.CREATE_NO_WINDOW)
        return result
    except subprocess.CalledProcessError as e:
        return f"命令执行出错：{e.output}"


# 字典转换为各个字符集列表
sjsj_char_sets = {
    '数字': string.digits,
    '小写字母': string.ascii_lowercase,
    '大写字母': string.ascii_uppercase,
    '特殊字符': string.punctuation
}


def generate_command(length=8, numbers=0, small_letters=0, large_letters=0, special_chars=0):
    """确定可用字符集合"""
    all_chars = ''
    if numbers:
        all_chars += sjsj_char_sets['数字']
    if small_letters:
        all_chars += sjsj_char_sets['小写字母']
    if large_letters:
        all_chars += sjsj_char_sets['大写字母']
    if special_chars:
        all_chars += sjsj_char_sets['特殊字符']
    # 验证至少有一个字符类别被选中
    if not all_chars or length <= 0:
        logger.error("至少要选择一种字符类别来生成密码")
        raise ValueError("至少要选择一种字符类别来生成密码")
    # 生成随机密码
    if 0 < length < 10:
        password = "".join(random.sample(all_chars, length))
        return password
    elif length >= 10:
        password = ''.join(random.choice(all_chars) for _ in range(length))
        return password


def entry_time_s1(s1):
    """秒时间戳转本地时间"""
    try:
        time_str_s2 = ti.strftime("%Y-%m-%d %H:%M:%S", ti.localtime(int(s1)))
        logger.info(f"{s1}转换结果为：{time_str_s2}")
        return str(time_str_s2)
    except (OSError, ValueError):
        logger.error("输入的时间格式错误，请纠正后重新转换！")
        Messagebox.show_error(title="时间戳转换", message="输入的时间格式错误，请纠正后重新转换！")


def entry_time_ms1(ms1):
    """毫秒时间戳转本地时间"""
    try:
        ms = float(ms1) / 1000
        time_str_ms2 = datetime.datetime.fromtimestamp(ms).strftime("%Y-%m-%d %H:%M:%S")
        logger.info(f"{ms1}转换结果为：{time_str_ms2}")
        return str(time_str_ms2)
    except (OSError, ValueError):
        logger.error("输入的时间格式错误，请纠正后重新转换！")
        Messagebox.show_error(title="时间戳转换", message="输入的时间格式错误，请纠正后重新转换！")


def entry_time_us1(us1):
    """微秒时间戳转换本地时间"""
    utc_dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(microseconds=int(us1))
    beijing_dt = utc_dt + datetime.timedelta(hours=8)
    beijing_out_us = beijing_dt.strftime('%Y-%m-%d %H:%M:%S.%f')
    logger.info(f"当前微秒级时间戳：{beijing_out_us}")
    return str(beijing_out_us)[:-7]


def time_stamp_s(s1):
    """本地时间转换为s时间戳"""
    try:
        timeStamp2 = int(ti.mktime(ti.strptime(s1, "%Y-%m-%d %H:%M:%S")))
        logger.info(f"{s1}当前秒级转换为：{timeStamp2}")
        return timeStamp2
    except ValueError:
        logger.error("输入的时间格式错误，请纠正后重新转换！")
        Messagebox.show_error(title="北京时间转时间戳", message="输入的时间格式错误，请纠正后重新转换！")


def time_stamp_ms(ms1):
    """本地时间转换为ms时间戳"""
    try:
        timeStamp2 = datetime.datetime.strptime(ms1, '%Y-%m-%d %H:%M:%S').timestamp()
        print(timeStamp2)
        timestamp_ms = int(timeStamp2) * 1000
        logger.info(f"{ms1}当前秒级转换为：{timestamp_ms}")
        return timestamp_ms
    except ValueError:
        logger.error("输入的时间格式错误，请纠正后重新转换！")
        Messagebox.show_error(title="北京时间转时间戳", message="输入的时间格式错误，请纠正后重新转换！")


def time_stamp_us(us1):
    """本地时间转换为us时间戳"""
    try:
        current_time = datetime.datetime.strptime(us1, '%Y-%m-%d %H:%M:%S')
        timestamp_s = int(current_time.timestamp())
        timestamp_us = timestamp_s * 1000000 + current_time.microsecond
        logger.info(f"{us1}当前秒级转换为：{timestamp_us}")
        return timestamp_us
    except ValueError:
        logger.error("输入的时间格式错误，请纠正后重新转换！")
        Messagebox.show_error(title="北京时间转时间戳", message="输入的时间格式错误，请纠正后重新转换！")


def current_timestamp():
    """获取秒为单位的本地时间戳"""
    inttimes = int(ti.time())
    return inttimes


def current_timestamp_ms():
    """获取毫秒为单位的本地时间戳"""
    inttimems = int(ti.time()) * 1000
    return inttimems


def current_timestamp_us():
    """获取微秒为单位的本地时间戳"""
    current_time = datetime.datetime.now()
    timestamp_us = (current_time.timestamp() * 1000000) + current_time.microsecond
    return int(timestamp_us)


def compare_jsons(json_entry1, json_entry2, output_text, tkend):
    """比较json文件"""
    json_str1 = json_entry1.get("1.0", tkend).strip()
    json_str2 = json_entry2.get("1.0", tkend).strip()
    try:
        data1 = json.loads(json_str1)
        data2 = json.loads(json_str2)
        json_str1 = json.dumps(data1, indent=4, sort_keys=True)
        json_str2 = json.dumps(data2, indent=4, sort_keys=True)
        diff = difflib.unified_diff(json_str1.splitlines(), json_str2.splitlines(), fromfile='JSON 1', tofile='JSON 2')
        decoded_diff = []

        for line in diff:
            # 解码可能存在的Unicode转义序列，使其在文本框中正确显示
            decoded_line = line.encode('latin1').decode('unicode_escape')
            decoded_diff.append(decoded_line)
        if not decoded_diff:
            output_text.delete(1.0, tkend)
            output_text.insert(tkend, "两个JSON文件内容完全相同。")
            return
        output_text.delete(1.0, tkend)
        for line in decoded_diff:
            output_text.insert(tkend, line + '\n')

    except json.JSONDecodeError:
        output_text.delete(1.0, tkend)
        output_text.insert(tkend, "输入的不是有效的JSON格式，请检查后重新输入。")
    except Exception as e:
        output_text.delete(1.0, tkend)
        output_text.insert(tkend, f"发生错误：{str(e)}")


def get_stored_wifi_networks():
    """
    获取所有存储的WiFi网络配置文件
    """
    command = "netsh wlan show profiles"
    try:
        output = subprocess.check_output(command, shell=True, text=True)
        logger.info(f"查询结果：{output}")
        # profiles = [line.split(": ")[1] for line in output.split("\n") if "所有用户配置文件 : " in line]
        # print(profiles)
        profiles = re.findall(r"所有用户配置文件 : (.+)", output, re.MULTILINE)
        return profiles
    except:
        print("数据为空")
        return None



def get_wifi_network_details(wifi_name):
    """
    获取指定SSID的WiFi网络的详细信息
    """
    command = f"netsh wlan show profiles name={wifi_name} key=clear"
    try:
        output = subprocess.check_output(command, shell=True, text=True)
        # 解析输出以获取密码
        password_search = re.search(r"关键内容\s*:\s*(\S+)", output)
        wifi_pwd = password_search.group(1) if password_search else None
        if wifi_pwd is None:
            texts = subprocess.check_output(f'netsh wlan show profiles name="{wifi_name}" key=clear', shell=True,
                                            text=True)
            colon_position = texts.find('关键内容            :')
            if colon_position != -1:
                key_content = texts[colon_position + len('关键内容            :'):].strip().splitlines()
                return key_content[0]
            else:
                return "未查询到密码"
        return wifi_pwd
    except subprocess.CalledProcessError as e:
        print(f"Error: {e}")
        return None


def wifi_run():
    """执行程序"""
    ssid_pwd = []
    stored_networks = get_stored_wifi_networks()
    if stored_networks:
        for ssid in stored_networks:
            password = get_wifi_network_details(ssid)
            # print(f"SSID: {ssid}, 密码: {password}")
            ssid_pwd.append((ssid, password))
        return ssid_pwd
    else:
        logger.warning("No wifi")
        return " "

